package com.tools.demo.login;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tools.demo.login.secret.RsaPrivateKey;
import com.tools.demo.login.secret.SecretKey;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 登录验证
 * 
 * @author mfk
 */
@RestController
public class SysLoginController
{

    String codeUrl = "https://pass.jscz.org.cn/czweb-server/oauth/authorize?client_id=9b945920-4e77-4702-bdfe-1e02ba522e58&response_type=code&scope=basic&redirect_uri=https://gxj.jscz.org.cn/gx_portal/portal";

    @PostMapping("/loginIdaas")
    public Object loginIdaas(@RequestBody LoginBody loginBody) throws Exception
    {
//        // 测试=============
//        String nickName2 = "贺家乐";
//        String certNo2 = "321081198105308117"; // 身份证号
//        String accTK = "9940955";
//        // 生成本系统的令牌，同时保存该用户当前登录的idaas的idToken和相关的信息
//        String token2 = loginService.loginIdaas(certNo2, accTK);
//
//        AjaxResult result2 = AjaxResult.success();
//        result2.put(Constants.TOKEN, token2);
//        result2.put("accessToken", accTK);
//        result2.put("certNo", certNo2);
//        result2.put("nickName", nickName2);
//
//        if(true == true) return result2;
//        // 测试=============



        // 返回参数初始化
        Map<String,Object> map = new HashMap<>();

        // 验证loginCode得到用户信息
        String loginCode = loginBody.getLoginCode();
        if(StringUtils.isEmpty(loginCode))
        {
            throw new Exception("系统错误：loginCode不能为空，请联系管理员！");
        }

//        String redirectUrl = "http://localhost:8010/portal";
        String redirectUrl = "https://gxj.jscz.org.cn/gx_portal/portal";
        String clientId = "9b945920-4e77-4702-bdfe-1e02ba522e58";
        String clientSecret = "4808db5c-781d-477b-b213-c2981d958912";
        String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL+IvLFpuZ5rIqZvcR/kXFTxnEW7PSUyZ0st/D8GzXzQL9RHVTbBKZlKXwVuLA6DrOdA302vzJZfJuYo4whJ3n8CAwEAAQ==";
        String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAv4i8sWm5nmsipm9xH+RcVPGcRbs9JTJnSy38PwbNfNAv1EdVNsEpmUpfBW4sDoOs50DfTa/Mll8m5ijjCEnefwIDAQABAkEAoo9kT1ODVkBp1UbKhZ3k+7dgwhJLsDFaWAV8jOWyLBZwF3l7C1pWchqVyyTd5VtzEOmySzVUClO4osgssOA5AQIhAPbePfSB8b51pC/p8NkfOTxzfZcCkOf/k4OboOMIfwCBAiEAxp6ALprt2cBpaziCYu1VSjDQB7Z7nwZxH1QVBmMZXv8CIQCjmhUk/RjgR8ZPmpHq0i50SXVppmGx3kY8ad7tlqvUAQIgL15x16ufekVHXwj1H77WjoEhvBUrWnvg0sXs1b8gt+UCIGm3Ozkd4lnY8Lcm0j1LFftjF8pYHQ41nSSCncNT3nOr";

        String baseUrl = "https://pass.jscz.org.cn/czweb-server";
        String getTokenUrl = baseUrl + "/oauth/token?grant_type=authorization_code&code="+loginCode+"&scope=basic&redirect_uri=" + redirectUrl;
        String getUserUrl = baseUrl + "/share/user";
        HttpClient httpClient  = HttpClientBuilder.create().build();
        // 3.发送请求接取返回值
        HttpPost post;
        post = new HttpPost(getTokenUrl);
        Base64.Encoder base64Encoder = Base64.getEncoder();
        String clientBase64 = new String(base64Encoder.encode((clientId+":"+clientSecret).getBytes(StandardCharsets.UTF_8)));
        post.setHeader("Authorization", "Basic " + clientBase64);

        HttpResponse response = httpClient.execute(post);

        JSONObject params = new JSONObject();
        // 将请求返回数据转为JSONObject
        params = JSON.parseObject(EntityUtils.toString(response.getEntity(),"UTF-8"));
        String accessToken = params.getString("access_token");
        if(!StringUtils.isEmpty(accessToken))
        {
            // 如果拿到access_token
            // 则获取用户基本信息
            post = new HttpPost(getUserUrl);
            post.setHeader("Authorization", "Bearer " + accessToken);
            response = httpClient.execute(post);
            params = JSON.parseObject(EntityUtils.toString(response.getEntity(),"UTF-8"));
            if (params.getInteger("code")==200)
            {
                JSONObject data = params.getJSONObject("data");
                String userInfoCrypt = data.getString("userInfo");
                if(StringUtils.isEmpty(userInfoCrypt) || !userInfoCrypt.contains(","))
                {
                    throw new Exception("错误：用户信息内容不正确，请联系管理员。");
                }

//                    String[] tmp = userInfoCrypt.split(",");
//                    if(tmp.length != 2)
//                    {
//                        throw new Exception("错误：用户信息格式不对，请联系管理员");
//                    }
//                    // 密钥段
//                    String aesKeyRSA = tmp[0];
//                    // 密文段
//                    String contentBase64 = tmp[1];
//
//                    // Rsa解密密钥得到aesKey
//                    RsaPrivateKey rsaPrivateKey = new RsaPrivateKey(privateKey);
//                    String aesKey = rsaPrivateKey.decrypt(aesKeyRSA);
//
//                    // base64解密密文段
//                    String contentAes = new String(Base64.getDecoder().decode(contentBase64));
//                    // aesKey解密密文段
//                    AesKey aesKeyObj = new AesKey(aesKey);
//                    String content = aesKeyObj.decrypt(contentAes);

                // 解密userInfo密文
                String decrypt = new SecretKey(new RsaPrivateKey(privateKey)).decrypt(userInfoCrypt);
                // 解析userInfo
                JSONObject userInfoObj = JSON.parseObject(decrypt);
                String userName = userInfoObj.getString("username");
                String nickName = userInfoObj.getString("nickname");
                String certType = userInfoObj.getString("certType");
                String certNo = userInfoObj.getString("certNo"); // 身份证号
                // 生成本系统的令牌，同时保存该用户当前登录的idaas的idToken和相关的信息
//                String token = loginService.loginIdaas(certNo, accessToken);

                Map<String,Object> result = new HashMap<>();
//                result.put("token", token);
                result.put("accessToken", accessToken);
                result.put("certNo", certNo);
                result.put("nickName", nickName);

                return result;
            }
            else {
                return "获取用户基本信息失败："+params.getInteger("code")+"  "+params.getString("msg");
            }
        }
        else
        {

            return "获取access_token失败！";
        }

    }




}
